package com.ruoyi.kjy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.kjy.domain.RoomReservation;
import com.ruoyi.kjy.domain.Rooms;
import com.ruoyi.kjy.service.RoomReservationService;
import com.ruoyi.kjy.service.RoomsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;

/**
 * @Description:
 * @Author: Hi，Wang
 * @Date: 11/10,0010 20:35
 */


@RestController
@RequestMapping("/roomReservation")
public class RoomReservationController extends BaseController {


    @Autowired
    private RoomsService roomsService;

    @Autowired
    private RoomReservationService roomReservationService;

    // 查看我的预约
    @GetMapping("/list")
    public AjaxResult list(Long current, Long size, RoomReservation roomReservation) {
        QueryWrapper<RoomReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("update_time");

//        roomReservation.setUserId(SecurityUtils.getUserId());
        queryWrapper.setEntity(roomReservation);
        if (Objects.isNull(current)) {
            current = 1l;
        }
        if (Objects.isNull(size)) {
            size = 10l;
        }
        if (size >= 20l) {
            size = 20l;
        }

        return AjaxResult.success(roomReservationService.page(new Page<>(current, size), queryWrapper));
    }


    @GetMapping("/listMy")
    public AjaxResult listMy(Long current, Long size, RoomReservation roomReservation) {
        QueryWrapper<RoomReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("update_time");
        roomReservation.setUserId(SecurityUtils.getUserId());
        queryWrapper.setEntity(roomReservation);
        if (Objects.isNull(current)) {
            current = 1l;
        }
        if (Objects.isNull(size)) {
            size = 10l;
        }
        if (size >= 20l) {
            size = 20l;
        }

        return AjaxResult.success(roomReservationService.page(new Page<>(current, size), queryWrapper));
    }





    //    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id) {
//        return AjaxResult.success(roomsService.getById(id));
//    }
//
//
    @Log(title = "预约会议室", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RoomReservation roomReservation) {

        if (roomReservation.getStartTime().isAfter(roomReservation.getEndTime())) {
            return error("开始时间不能大于结束时间");
        }

        if (roomReservation.getEndTime().isBefore(LocalDateTime.now())) {
            return error("结束时间不能小于当前时间");
        }

        Rooms byId = roomsService.getById(roomReservation.getRoomId());
        System.out.println(roomReservation.getId());
        if (byId == null) return error("该会议室不存在"); // 会议室不存在
        if (checkRoom(roomReservation)) {
            return error("该时间段已有预约，请选择其他时间段");
        }
        roomReservation.setUserId(SecurityUtils.getUserId());
        roomReservation.setStatus(0);
        boolean save = roomReservationService.save(roomReservation);
        return toAjax(save);
    }

    private boolean checkRoom(RoomReservation roomReservation) {

        QueryWrapper<RoomReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("room_id", roomReservation.getRoomId()) // 查询房间ID
                .and(
                        wrapper -> wrapper
                                .lt("start_time", roomReservation.getEndTime()) // 现有预约的开始时间小于当前预约的结束时间
                                .gt("end_time", roomReservation.getStartTime()) // 现有预约的结束时间大于当前预约的开始时间
                )
//                .ne("id", roomReservation.getId()) // 排除当前预约ID（用于修改时检查）
                .ne("status", 2); // 排除已取消或已结束的预约（假设 2 为已取消或已结束的状态）

        long count = roomReservationService.count(queryWrapper); // 查询符合条件的预约数量
        return count > 0; // 如果找到冲突的预约，返回 true
    }

    //
    @Log(title = "预约会议室", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RoomReservation roomReservation) {

        UpdateWrapper<RoomReservation> updatableField = new UpdateWrapper<>();
        // TODO
        updatableField.eq("id", roomReservation.getId());
   //     updatableField.eq("user_id", SecurityUtils.getUserId());
//        updatableField.setEntity(roomReservation);
//        updatableField.setEntity()
        updatableField.set("status", roomReservation.getStatus());

        return toAjax(roomReservationService.update(updatableField));
    }
//
//    @Log(title = "众创空间", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids) {
//        return toAjax(roomsService.removeByIds(Arrays.asList(ids)));
//    }


}
